package com.dns.test.client;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.DatagramPacket;

import com.dns.message.DNS_Message;
import com.dns.util.Constants;

public class MessageReceiverThread extends Thread{

	public void run(int messageNumber)
	{
		try
		{
			while(true)
			{
				byte []dataBuffer = new byte[Constants.DATA_BUFFER_SIZE];
				DatagramPacket receivedPacket;
				receivedPacket = new DatagramPacket(dataBuffer, dataBuffer.length);
				DNSClient.clientSocket.receive(receivedPacket);
				processPacket(receivedPacket);
			}
			
		
		}catch(Exception exception)
		{ 
			System.err.println("Exception @SecondaryServer: "+exception.getMessage());
		}		
	}
	
	private void processPacket(DatagramPacket receivedPacket)
	{
		ByteArrayInputStream byteInputStream =null;
		ObjectInputStream objectInputStream = null;
		byteInputStream = new ByteArrayInputStream(receivedPacket.getData());
		DNS_Message receivedMsg = null;
		try{			
			objectInputStream = new ObjectInputStream(byteInputStream);
			receivedMsg = (DNS_Message)objectInputStream.readObject();
			DNSClient.printMessage(receivedMsg);
		}
		catch (IOException e) {
			System.out.println(this.getClass().getName()+" : Exception while de-serializing the DNS_Message object");
			e.printStackTrace();
		}
		catch (ClassNotFoundException e) {
			System.out.println(this.getClass().getName()+" : Exception while creating the deserialized DNS_Message object");
			e.printStackTrace();
		}		
	}
	
}
